<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑问卷' : '新建问卷'"
    width="400px"
    @close="handleClose"
    destroy-on-close
  >
    <el-form :model="form" label-width="60px">
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="请输入问卷标题" />
      </el-form-item>
      <el-form-item label="说明">
        <el-input
          type="textarea"
          v-model="form.description"
          placeholder="请输入问卷说明"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">
        {{ isEdit ? '保存' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  modelValue: Boolean,
  isEdit: { type: Boolean, default: false },
  editData: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(props.modelValue)

watch(visible, (val) => emit('update:modelValue', val))
watch(() => props.modelValue, (val) => (visible.value = val))

const form = ref({
  id: '',
  title: '',
  description: ''
})

// 当编辑数据变化时更新表单
watch(
  () => props.editData,
  (val) => {
    form.value = val ? { ...val } : { id: '', title: '', description: '' }
  },
  { immediate: true }
)

// 提交表单
const handleSubmit = async () => {
  if (!form.value.title) {
    ElMessage.warning('请输入问卷标题')
    return
  }

  const url = props.isEdit
    ? '/questionnaire/updateQuestionnaire'
    : '/questionnaire/addQuestionnaire'

  try {
    const res = await request.post(url, form.value)
    if (res.data?.code === 200) {
      ElMessage.success(props.isEdit ? '修改成功' : '创建成功')
      emit('success') // 通知父组件刷新表格
      handleClose()
    } else {
      ElMessage.error(res.data?.msg || '操作失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 安全关闭弹窗
const handleClose = () => {
  visible.value = false
  // 延迟清空表单，避免动画中 DOM 操作报错
  nextTick(() => {
    form.value = { id: '', title: '', description: '' }
  })
}
</script>
